package JasPerl::JSTL::Core::RedirectTag;

use 5.010;
use strict;
use warnings;

use parent qw{
    JasPerl::TagExt::JspBodyTag
    JasPerl::JSTL::Core::ParamParent
};

use JasPerl::JSTL::Core::Exceptions;
use URI;

sub set_context {
    JasPerl::JSTL::Core::UnsupportedAttributeException->throw('redirect', 'context');
}

sub set_url {
    $_[0]->{uri} = URI->new($_[1]);
}

sub redirect {
    my ($self, $uri) = @_;
    my $context = $self->get_jsp_context();
    my $response = $context->get_response();

    if ($uri->scheme) {
        $response->send_redirect("$uri");
    } else {
        $response->send_redirect($response->encode_redirect_url("$uri"));
    }

    JasPerl::SkipPageException->throw(); # skip rest of page
}

sub do_tag {
    my $self = shift;
    JasPerl::JSTL::Core::NullAttributeException->throw('redirect', 'url')
        unless $self->{uri};
    $self->SUPER::do_tag();

    my $uri = $self->{uri};
    # TODO: handle context attribute
    if (!$uri->scheme && $uri->path =~ m{^/}) {
        my $context = $self->get_jsp_context();
        my $request = $context->get_request();
        $uri->path($request->get_context_path() . $uri->path)
    }
    $self->redirect($uri);
}

1;
